//  this library.
import 'package:flutter/material.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/view_util.dart';

/// 自定义提示显示格式方法
typedef TipsFormatFun = Text Function({
  required int qCount,
  required int num,
  required double progress,
});

/// 章节显示题目量组件
class VideoShowPercentWidget extends StatelessWidget {
  final bool isFinished;

  /// 试题总数
  final int qCount;

  /// 做题数量
  final int num;

  /// 是否显示题目数量，自定义提示时可以不填，默认值为true。
  /// true：num/aCount 道,false:百分比进度
  final bool? showQuestion;

  /// 提示后缀
  final String? tipsSuffix;

  /// 自定义显示格式方法
  final TipsFormatFun? tipsFormatFun;

  const VideoShowPercentWidget({
    super.key,
    required this.qCount,
    required this.num,
    this.showQuestion = true,
    this.tipsSuffix,
    this.tipsFormatFun,
    this.isFinished = false,
  });

  @override
  Widget build(BuildContext context) {
    // 获取进度
    double progress = _getProgress();
    return Row(
      mainAxisSize: MainAxisSize.max,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        SizedBox(
          height: 8,
          width: 120,
          child: LinearProgressIndicator(
            value: progress,
            backgroundColor: colorWhite2,
            valueColor: const AlwaysStoppedAnimation(colorBlue1),
            borderRadius: BorderRadius.circular(6),
          ),
        ),
        hiSpace(width: 16),
        // Text("11111"),
        _rightItem(progress: progress),
        hiSpace(width: 16),
        if (isFinished)
          SizedBox(
            width: 50,
            child: Text(
              "已完成",
              style: TextStyle(color: colorGreen1),
            ),
          )
      ],
    );
  }

  /// 右边提示组件显示
  _rightItem({required double progress}) {
    if (tipsFormatFun != null) {
      return tipsFormatFun!(
        qCount: qCount,
        num: num,
        progress: progress,
      );
    } else {
      return showQuestion! ? _questionNum() : _progressText(progress);
    }
  }

  /// 显示进度 % 方法
  _progressText(double progress) {
    int pro = (progress * 100).toInt();
    return Text(
      "$pro${tipsSuffix ?? "%"}",
      style: FontUtil.fontGrey2(14),
    );
  }

  /// 显示题目数方法
  _questionNum() {
    return Text.rich(
      TextSpan(
        children: [
          TextSpan(
              text: num.toString(),
              style: num > 0 ? FontUtil.fontBlue1(24) : FontUtil.fontGrey2(24)),
          TextSpan(
              text: "/$qCount${tipsSuffix ?? "道"}",
              style: FontUtil.fontGrey2(24)),
        ],
      ),
    );
  }

  /// 计数进度方法
  double _getProgress() {
    if (num > 0) {
      if (qCount == 0) {
        return 0.00;
      }
      double value = double.parse((num / qCount).toStringAsFixed(2));
      if (value >= 1) {
        return 1.00;
      }
      if (value <= 0.01) {
        return 0.01;
      }
      return value;
    }
    return 0.00;
  }
}
